package com.self.console.web.interceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.self.console.dto.AdminDto;
import com.self.console.web.controller.back.common.BackController;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sangame.sow.ssh.annotation.ActionMode;
import com.sangame.sow.ssh.annotation.PermissionPoint;
import com.sangame.sow.ssh.orm.hibernate.ThreadLocalHolder;
import com.sangame.sow.ssh.orm.hibernate.support.JsonWrapper;

/**
 * 权限过滤
 */
public class PermissionInterceptor extends HandlerInterceptorAdapter {
	
	private final static Logger LOG = LoggerFactory.getLogger(PermissionInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		BackController backAction = (BackController)handlerMethod.getBean();
		
		AdminDto user = backAction.getUser();
		if(user == null) {
			ThreadLocalHolder.set(null);
			return true;
		} else {
			String operCode = null;
			Method method = handlerMethod.getMethod();
			PermissionPoint pp = method.getAnnotation(PermissionPoint.class);
			if(pp != null && pp.point() != null) {
				operCode = pp.point();
			}
			
			if(operCode == null || user.hasOper(operCode)) { //pass
			    ThreadLocalHolder.set(user.getRealName());
				return true;
			} else { // not pass
				if(LOG.isWarnEnabled()){
					LOG.warn("权限不足，user：{}，url：{}", new Object[]{user.getRealName(), request.getRequestURI()});
				}
				forwarePage(request, response, handler);
				return false;
			}
		}
	}
	
	private void forwarePage(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException {
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		Method method = handlerMethod.getMethod();
		ActionMode actionMode = method.getAnnotation(ActionMode.class);
		
		String contextPath = request.getContextPath();
		
		if(actionMode == null || StringUtils.isBlank(actionMode.value())) {
			String url = String.format("%s/back/common/jump.htm?message=%s&redirectUrl=%s", 
					contextPath,URLEncoder.encode("权限不足", "UTF-8"),
					URLEncoder.encode(contextPath + "/back/frame/main.htm", "UTF-8"));
			
			response.sendRedirect(url);
		} else if(actionMode.value().equals(ActionMode.PAGE)) {
			String url = String.format("%s/back/common/jump.htm?message=%s&redirectUrl=%s", 
					contextPath,URLEncoder.encode("权限不足", "UTF-8"),
					URLEncoder.encode(contextPath + "/back/frame/main.htm", "UTF-8"));
			
			response.sendRedirect(url);
		} else if(actionMode.value().equals(ActionMode.JSON)) {
			response.setContentType("application/json");
			ObjectMapper objectMapper = new ObjectMapper();
			objectMapper.writeValue(response.getOutputStream(), new JsonWrapper<Object>(false, "权限不足", null));
		}
	}
	
}

